package kr.hkit.androidcomplete03.ch22;

import java.util.ArrayList;
import java.util.Random;

import kr.hkit.androidcomplete03.R;
import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.MotionEvent;
import android.view.View;

public class Reflection extends Activity {
	MyView mv;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		mv = new MyView(this);
		setContentView(mv);
	}

	class MyView extends View {
		Bitmap mBack;
		ArrayList<Ball> arBall = new ArrayList<Ball>();
		final static int DEALY = 50;
		final static int RAD = 24;
		
		public MyView(Context context) {
			super(context);
			mBack = BitmapFactory.decodeResource(context.getResources(),
					R.drawable.family);
			mHandler.sendEmptyMessageDelayed(0, DEALY);
		}

		// 새로운 볼 생성
		public boolean onTouchEvent(MotionEvent event) {
			if (event.getAction() == MotionEvent.ACTION_DOWN) {
				Ball NewBall = Ball.Create((int) event.getX(),
						(int) event.getY());
				arBall.add(NewBall);
				invalidate();
				return true;
			}
			return false;
		}

		// 화면 그리기
		public void onDraw(Canvas canvas) {
			Rect dst = new Rect(0, 0, getWidth(), getHeight());
			canvas.drawBitmap(mBack, null, dst, null);
			for (int idx = 0; idx < arBall.size(); idx++) {
				arBall.get(idx).Draw(canvas);
			}
		}

		// 볼 이동 및 화면 무효화
		Handler mHandler = new Handler() {
			public void handleMessage(Message msg) {
				Ball B;
				for (int idx = 0; idx < arBall.size(); idx++) {
					B = arBall.get(idx);
					B.Move(getWidth(), getHeight());
					if (B.count > 4) {
						arBall.remove(idx);
						idx--;
					}
				}

				invalidate();
				mHandler.sendEmptyMessageDelayed(0, DEALY);
			}
		};
	}
}
